import Vue from 'vue'
import mask from './loadingmask.vue'
const maskConstructor = Vue.extend(mask)

maskConstructor.prototype.close = function () {
    if (this.options.timeOut) {
        clearTimeout(this.options.timeOut)
    }
    if(!this.$el.parentNode) return
    this.$el.parentNode.removeChild(this.$el)
    this.$destroy()
}

const maskInstance = function (dom, options = {}) {
    let maskoptions = {
        title: '下载中',
        background: 'rgba(0,0,0,0.4)',
        color: '#fff',
        antiClockwise: false,
        progress: true,
        full: false,
    }
    let maskEl = new maskConstructor({
        el: document.createElement('div')
    })
    Vue.nextTick(() => {
        if (dom) {
            let targetDomArry = null
            try {
                targetDomArry = document.querySelectorAll(dom)
                if (targetDomArry.length > 1) {
                    throw "请传入唯一的DOM节点"
                }
            } catch (error) {
                throw '请传入正确的CSS选择器'
            }
            let targetDom = targetDomArry[0]
            let {
                x,
                y,
                width,
                height,
                top,
                left
            } = targetDomArry[0].getBoundingClientRect()
            // let targetDomBounding = targetDomArry[0].getBoundingClientRect()
            // targetDom.style.position ? '' : targetDom.style.position = 'relative'
            if (options.full) {
                maskEl.$el.style.height = 100 + 'vh'
                maskEl.$el.style.width = 100 + 'vw'
                maskEl.$el.style.top = 0
                maskEl.$el.style.left = 0
            } else {
                // maskEl.$el.style.height = height + 'px'
                // maskEl.$el.style.width = width + 'px'
                // maskEl.$el.style.top = top + 'px'
                // maskEl.$el.style.left = left + 'px'
            }


            Object.assign(maskoptions, options)
            maskEl.options = maskoptions
            maskEl.tipsArry = (maskoptions.title+'...').split('')
            maskEl.dom = dom
            if (options.time) {
                maskEl.options.timeOut = setTimeout(() => {
                    maskEl.$el.parentNode.removeChild(maskEl.$el)
                }, options.time)
            }
            targetDom.appendChild(maskEl.$el)
        } else {
            throw '请传入css选择器'
        }
    })

    return maskEl
}
export default maskInstance
